/*
 * DCE400服务系统 -- 后端服务接口 -- 数据访问层 -- 工单数据访问
 * 包括：
 */
package dao

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"go.uber.org/zap"
	"strings"
	"time"
)

//********************************************
//Func  ：查询部门列表，分页查询。
//Method：
//Usage ：
//********************************************
func QueryDepartmentList(page, pageSize int) (int64, []*entity.Department, error) {
	offset := (page - 1) * pageSize
	session := db.Session().Table("department2") //工单
	defer session.Close()

	if pageSize > 0 {
		session.Limit(pageSize, offset)
	} else { //若pageSize<=0，则显示全部

	}
	depts := []*entity.Department{}
	total, err := session.Where("status=?", entity.EDepartmentStatus_Normal).FindAndCount(&depts)
	if err != nil {
		return 0, nil, err
	}
	return total, depts, nil
}

//返回一个map，部门ID为key
func QueryDepartmentMap() map[int64]*entity.Department {
	outputMap := make(map[int64]*entity.Department)
	session := db.Session().Table("department2")
	defer session.Close()
	depts := []*entity.Department{}
	err := session.Where("status=?", entity.EDepartmentStatus_Normal).Find(&depts)
	if err != nil {
		return nil
	}
	for _, dept := range depts {
		outputMap[dept.DeptId] = dept
	}
	return outputMap
}

//********************************************
//Func  ：查询数据库：根据部门ID，查询部门详情
//Method：GET
//Usage ：
//********************************************
func QueryDeptartmentDetail(Id int64) (*entity.Department, error) {
	session := db.Session().Table("department2") //.Where("id=?",operatorId).Get(&operator)
	defer session.Close()

	var dept entity.Department
	has, err := session.Where("dept_id=?", Id).Get(&dept)
	if err != nil || has == false {
		return nil, err
	}
	return &dept, nil
}

//********************************************
//Func  ：添加新部门
//Method：POST
//Usage ：
//********************************************
func CreateDepartment(dept entity.Department) (*entity.Department, error) {
	var err error
	if len(strings.TrimSpace(dept.DeptName)) <= 0 { //姓名（必填）/单位名称
		return nil, errors.New("name is none")
	}

	dept.CreatedAt = time.Now()
	dept.DeptId = util.GenSnowflakeInt64()
	dept.Status = entity.EDepartmentStatus_Normal
	global.Log.Info("InsertDepartment: ", zap.Any("dept:", dept))

	session := db.Session().Table("department2")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return nil, errors.New("db session begin failed.")
	}

	_, err = session.Insert(&dept) //插入
	if err != nil {
		session.Rollback()
		return nil, err
	}
	err = session.Commit()
	if err != nil {
		return nil, err
	}

	return &dept, nil
}

//********************************************
//Func  ：更新信息部门
//Method：POST
//Usage ：
//********************************************
func UpdateDepartment(dept entity.Department, cols string) error {
	var err error
	if len(strings.TrimSpace(dept.DeptName)) <= 0 {
		return errors.New("dept name is none")
	}
	if dept.DeptId <= 0 {
		return errors.New("dept id is none")
	}

	session := db.Session().Table("department2")
	defer session.Close()
	err = session.Begin()
	if err != nil {
		return err
	}

	if len(cols) > 0 {
		_, err = session.Where("dept_id=?", dept.DeptId).
			Cols(cols).
			Update(dept) //更新
	} else {
		_, err = session.Where("dept_id=?", dept.DeptId).
			Cols("dept_name,readme,dept_head,dept_head_id,status").
			Update(dept) //更新
	}

	if err != nil {
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}

//********************************************
//Func  ：删除部门
//Method：DELETE
//Usage ：部门-删除
//********************************************
func DeleteDepartment(deptId int64) error {
	if deptId <= 0 {
		return errors.New("未指定部门ID信息")
	}
	session := db.Session().Table("department2")
	defer session.Close()
	session = session.Where("dept_id=?", deptId)
	session.Begin()
	cnt, err := session.Delete(&entity.Department{})
	if err != nil {
		session.Rollback()
		return err
	}
	if cnt <= 0 {
		session.Rollback()
		return errors.New("移除部门数量0")
	}
	err = session.Commit()
	return err
}
